package com.gxh.interceptor;

import com.gxh.constant.JwtClaimsConstant;
import com.gxh.context.BaseContext;
import com.gxh.properties.JwtProperties;
import com.gxh.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenCommonInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 拦截器方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前拦截到的是 Controller 的方法
        if (!(handler instanceof HandlerMethod)) {
            return true; // 放行静态资源等非控制器请求
        }

        String adminToken = request.getHeader(jwtProperties.getAdminTokenName());
        String userToken = request.getHeader(jwtProperties.getUserTokenName());

        try {
            if (adminToken != null) {
                log.info("解析 adminToken: {}", adminToken);
                Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), adminToken);
                Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
                BaseContext.setCurrentId(empId);
                log.info("当前管理员 ID: {}", empId);
                return true;
            }

            if (userToken != null) {
                log.info("解析 userToken: {}", userToken);
                Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), userToken);
                Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
                BaseContext.setCurrentId(userId);
                log.info("当前用户 ID: {}", userId);
                return true;
            }

            // 两个 token 都没有
            log.warn("请求未携带任何有效 token");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;

        } catch (Exception ex) {
            log.error("JWT 校验失败: {}", ex.getMessage(), ex);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }
}

